<template>
  <div class="meeting">
    <div class="little-data">
      <div style="margin:20px 0 0 50px;">
        <Select v-model="meetDefault" style="width:145px" @on-change="meetRoomSelect">
          <Option v-for="item in meetRoomList" :value="item.value" :key="item.value">{{ item.label }}</Option>
        </Select>
        <Button type="ghost" @click="saveCreateMeet" class="meetBtn">创建会议</Button>
      </div>
    </div>
    <div class="big-data">
      <full-calendar :events="events" @prev="prev" @event-selected="eventClick" @event-render="eventRender" :config="config" :defaultView="defaultView"></full-calendar>
    </div>
    <div>
      <!--<i id="poss" style="position:absolute;">325453647</i>-->
      <div id="poss" style="position:absolute;">
        <!--<i :full="full"></i>-->
        <!--<Poptip confirm @on-ok="ok" @on-cancel="cancel">-->
        <Poptip :title="fullTitle" :content="fullContent" v-model="visible" placement="right">
          <div slot="content" class="meetCard">
            <Row>
              <Col>
              <Card dis-hover>
                <p slot="title">
                  <i class="tilleRight">{{meetEvent.mesgTitle}}</i>
                  <b :class="meetEvent.status === '未开始' ? 'titleStatus noStart' : (meetEvent.status === '已完成'? 'titleStatus yesEnd' : (meetEvent.status === '执行中' ? 'titleStatus progress':''))"></b>
                </p>
                <p>
                  <Icon type="clock" />
                  <i>{{meetEvent.time}}</i>
                </p>
                <p>
                  <i>创建者：</i>
                  <i>{{meetEvent.mesgCreator}}</i>
                </p>
                <p>
                  <i>会议地点：</i>
                  <i>{{meetEvent.mesgAddress}}</i>
                </p>
              </Card>
              </Col>
            </Row>
            <a @click="editBtn">编辑</a>
            <a @click="deleteBtn">删除</a>
          </div>
        </Poptip>
      </div>
    </div>
    <!--申请会议弹出框-->
    <Modal v-model="createMeet" title="创建会议" :mask-closable="false" width="700px" class="modelStyle">
      <Row>
        <Col span="24">
        <Form :model="formLeft" label-position="left" :label-width="82" :rules="meetCheck" ref="meetForm">
          <Row>
            <Col span="11">
            <FormItem label="会议室选择" prop="model1">
              <Select v-model="formLeft.model1" style="width:220px" @on-change="formLeftSelect">
                <Option v-for="item in cityList" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </FormItem>
            </Col>
            <Col span="2" style="padding:20px;"></Col>
            <Col span="11">
            <FormItem label="会议地点">
              <Input v-model="formLeft.address" style="width:220px" disabled></Input>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="11">
            <FormItem label="会议标题" prop="meetTitle">
              <Input v-model="formLeft.meetTitle" style="width:220px"></Input>
            </FormItem>
            </Col>
            <Col span="2" style="padding:20px;"></Col>
            <Col span="11">
            <FormItem label="会议类型">
              <RadioGroup v-model="vertical">
                <Radio label="本地会议"></Radio>
                <Radio label="视频会议"></Radio>
              </RadioGroup>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="11">
            <FormItem label="申请人">
              <!-- <Input v-model="formLeft.applyPeople" style="width:220px"></Input> -->
              <Select v-model="formLeft.applyPeople" style="width:220px" @on-change="formPeopleSelect">
                <Option v-for="item in peopleList" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </FormItem>
            </Col>
            <Col span="2" style="padding:20px;"></Col>
            <Col span="11">
            <FormItem label="参会人数" prop="joinNum">
              <Input v-model="formLeft.joinNum" style="width:220px"></Input>
            </FormItem>
            </Col>
          </Row>
          <FormItem label="会议时间">
            <Row>
              <Col span="10">
              <FormItem prop="startTime">
                <DatePicker type="datetime" format="yyyy-MM-dd HH:mm" :options="dateLimit" v-model="formLeft.startTime" placeholder="选择开始时间" style="width: 220px"></DatePicker>
              </FormItem>
              </Col>
              <Col span="4" style="text-align: center">
              <i>-</i>
              </Col>
              <Col span="10">
              <FormItem prop="date">
                <DatePicker type="datetime" format="yyyy-MM-dd HH:mm" :options="dateLimit" v-model="formLeft.endTime" placeholder="选择结束时间" style="width: 220px"></DatePicker>
              </FormItem>
              </Col>
            </Row>
          </FormItem>
          <FormItem label="会议内容" prop="meetContent">
            <Input v-model="formLeft.meetContent" type="textarea" :rows="4" placeholder=""></Input>
          </FormItem>
        </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button type="ghost" @click="cancelCreate">取消</Button>
        <Button type="primary" @click="createMeetYes">确认</Button>
      </div>
    </Modal>
    <!--删除时间-->
    <Modal v-model="deleteModal" class-name="vertical-center-modal" @on-ok="deleteOk" @on-cancel="deleteModal = false" width="300">
      <p>确定删除所选会议？</p>
    </Modal>
  </div>
</template>
<script>
  let middle
  import fullCalendar from './test/Fullcent.vue'
  import 'fullcalendar/dist/locale/zh-cn'
  import './metting.css'
  import moment from 'moment'
  import { mapState, mapActions, mapGetters, mapMutations } from 'vuex'
  export default {
    data() {
      const numCheck = (rule, value, callback) => {
        var r = /^([0-9][0-9]*)$/
        if (value === '') {
          callback()
        }
        if (r.test(value) && Number(value) >= 0) {
          var s = (value + '').substring(0, 1)
          if ((value.length > 1) && (Number(s) === 0)) {
            return callback(new Error('请输入有效数字'))
          } else {
            callback()
          }
        } else {
          return callback(new Error('请输入有效数字'))
        }
      }
      const titleCheck = (rule, value, callback) => {
        if (value === '') {
          return callback(new Error('不能为空'))
        }
        if (value !== '') {
          return callback()
        } else {
          return callback(new Error('请输入有效数字'))
        }
        // const chenkValue = /^[0-9a-zA-Z-_—\u4e00-\u9fa5]{0,32}$/
        // if (value === '') {
        //   console.log('会议名称不能为空')
        //   callback(new Error('会议名称不能为空'))
        // } else if (!chenkValue.test(value)) {
        //   callback(new Error('请输入汉字、数字、字母、-、——、_，并且长度不能超过32！'))
        // } else {
        //   callback()
        // }
      }
      return {
        events: [],
        defaultView: 'month',
        config: {
          // eventClick: (event) => {
          //   this.selected = event;
          // },
          editable: false,
          allDaySlot: false, //agenda视图模式下，是否在日历上方显示all-day(全天)
          eventLimit: 5,
          eventLimitText: '更多',
          locale: 'zh-cn',
          slotDuration: '00:20:00',
          buttonText: { listMonth: '列表' },
          handleWindowResize: true,
          aspectRatio: 1.54, //设置日历单元格宽度与高度的比例
          minTime: '09:00:00', // 设置显示的时间从几点开始
          // maxTime: '21:00:00'	//设置显示的时间从几天结束
          eventColor: '#f8f8f8',
          eventBackgroundColor: "",
          eventBorderColor: "",
          eventTextColor: "#000000",
          selectable: false  //是否允许用户通过单击或拖动选择日历中的对象，包括天和时间。
          // themeSystem: 'bootstrap3'
        },
        selected: {},
        fullTitle: '',
        fullContent: '',
        visible: false,
        //会议详细信息
        meetEvent: {
          mesgTitle: '',
          time: '',
          status: '',
          mesgCreator: '',
          mesgAddress: ''
        },
        createMeet: false,
        vertical: '本地会议',
        dateLimit: {
          disabledDate(date) {
            return date && date.valueOf() > Date.now()
          }
        },
        formLeft: {
          model1: '',
          address: '',
          input3: '',
          meetTitle: '',
          meetType: '',
          applyPeople: '',
          joinNum: '',
          startTime: '',
          endTime: '',
          meetContent: ''
        },
        meetCheck: {
          joinNum: [
            { required: true, validator: numCheck, trigger: 'change' }
          ],
          meetTitle: [
            { required: true, validator: titleCheck, trigger: 'change' }
          ],
          startTime: [
            { required: true, validator: titleCheck, trigger: 'change' }
          ],
          model1: [
            { required: true, validator: titleCheck, trigger: 'change' }
          ],
          meetContent: [
            { required: true, validator: titleCheck, trigger: 'change' }
          ]
        },
        // 会议室
        cityList: [],
        // 人员
        peopleList: [],
        meetstart: '',
        meetEnd: '',
        space: '',
        deleteModal: false,
        middle: [],
        // 会议室列表
        meetRoomList: [],
        meetDefault: '',
        // 会议室ID
        roomPid: '',
        // 会议Id
        meetId: '',
        type: '',
        judgeEdit: false
      }
    },
    created() {
      this.memberSearch()
      // this.$http.put('/conference/1', {
      //   id: 1,
      //   pid: 1,
      //   title: '222',
      //   type: 0,
      //   proposer: '222',
      //   number: 8,
      //   startDate: '111',
      //   endDate: '333',
      //   content: '222'
      // }).then((res) => {
      //   console.log('/conference/:id', res)
      //   // commit('SET_MEETDATA', res)
      // }).catch(err => {
      //   console.log('post /conference:' + err)
      // })
      this.createEventsList()
      console.log(this.testData)
      this.createMettRoom().then(() => {
        console.log('this.createMettRoom', this.meetRoomData)
      }).catch(err => {
        console.log('getVideoAmountCount error: ' + err)
      })
      this.eventRender()
      this.formLeft.endTime = new Date()
    },
    components: {
      fullCalendar
    },
    computed: {
      ...mapState({
        testData: ({ meetManage }) => meetManage.testData,
        meetRoomData: ({ meetManage }) => meetManage.meetRoomData,
        allMemberList: ({ user }) => user.allMemberList
      })
    },
    watch: {
      meetRoomData() {
        this.meetRoomData.forEach(({ name, roomId }) => {
          this.meetRoomList.push({ label: name, value: name, roomId })
          this.cityList.push({ label: name, value: name, roomId })
        })
      },
      allMemberList() {
        this.allMemberList.forEach(({ realname, id }) => {
          this.peopleList.push({ label: realname, value: realname, id })
        })
      },
      model1(val) {
        console.log(val)
      }
    },
    methods: {
      ...mapMutations(['SET_MEETDATA', 'GET_MEETROOMDATA', 'GET_MEETLISTDATA', 'SAVE_MEMBERLIST']),
      ...mapActions(['createMetting', 'createMettRoom', 'createMeetList', 'changeMetting', 'deleteMetting', 'getMemberList']),
      memberSearch() { // 按人员模糊查询
        this.getMemberList('').then((suc) => {
          consle.log('111', this.allMemberList)
        }).catch((err) => {
        })
      },
      // 获取会议列表
      createEventsList() {
        this.createMeetList().then(() => {
          console.log('this.createMeetList', this.meetRoomData)
          this.events = JSON.parse(JSON.stringify(this.testData))
          console.log('this.createMeetList', this.meetRoomData)
        }).catch(err => {
          console.log('createMeetList error: ' + err)
        })
      },
      refreshEvents() {
        this.$refs.calendar.$emit('refetch-events');
      },

      removeEvent() {
        this.$refs.calendar.$emit('remove-event', this.selected);
        this.selected = {};
      },
      prev() {
        console.log(1234567)
      },
      // 事件渲染时触发
      eventRender(event, element, view) {
        // console.log('4567890-', event.start)
        // this.events = this.testData
        // this.events.forEach((item, index) => {
        //   if (this.events[index].status === '已完成') {
        //     this.events[index].color = '#19be6b'
        //     this.events[index].textColor = 'yellow'
        //   } else if (this.events[index].status === '执行中') {
        //     this.events[index].color = '#2d8cf0'
        //     this.events[index].textColor = 'yellow'
        //   } else {
        //     this.events[index].color = '#f7b84f'
        //     this.events[index].textColor = 'yellow'
        //   }
        // })
      },
      // 日期点击时触发
      eventSelected(event) {
        console.log('日期点击')
        this.selected = event;
      },
      // 事件点击
      eventClick(event, jsEvent, view) {
        console.log("事件点击↓↓↓eventClick↓↓↓", this.events)
        console.log('Current view: ', event)
        jsEvent.stopPropagation()
        var poss = document.getElementById('poss')
        this.visible = true
        poss.style.left = (jsEvent.pageX + 8) + "px"
        poss.style.top = (jsEvent.pageY - 13) + "px"
        this.meetEvent.mesgTitle = event.mtitle
        if (event.start && event.end) {
          this.meetEvent.time = event.start._i + '至' + event.end._i
        }
        // this.meetEvent.time = this.$moment(event.start._d * 1000).format('HH:mm') + '至' + this.$moment(event.end * 1000).format('HH:mm')
        this.meetEvent.status = event.status
        this.meetEvent.mesgCreator = event.applyPeople
        this.meetEvent.mesgAddress = event.meetAddress
        this.meetEvent.meetContent = event.meetContent
        console.log(this.meetEvent.status)
        this.space = event
      },
      // 日期点击 @event-created="eventCreated"
      eventCreated(...test) {
        console.log("↓↓↓select↓↓↓")
        console.log('日期点击dinaj')
        console.log(test);
        return false;
      },
      //编辑按钮
      editBtn() {
        console.log('编辑按钮', this.space)
        console.log('')
        console.log(new Date())
        this.judgeEdit = true
        this.visible = false
        this.createMeet = true
        this.formLeft.meetTitle = this.meetEvent.mesgTitle
        this.formLeft.startTime = this.space.start._i
        this.formLeft.endTime = this.space.end._i
        this.formLeft.applyPeople = this.space.applyPeople
        this.formLeft.address = this.space.meetAddress
        this.formLeft.joinNum = this.space.joinNum
        this.formLeft.meetContent = this.space.meetContent
        this.meetId = this.space.meetId
        this.roomPid = this.space.roomId
        this.meetRoomData.forEach((item, index) => {
          console.log('111', this.space.roomId, item.roomId)
          if (item.roomId === this.space.roomId) {
            this.formLeft.model1 = item.name
            this.formLeft.address = item.address
          }
        })
      },
      // 删除按钮
      deleteBtn() {
        console.log('删除按钮', this.space.title)
        this.visible = false
        this.deleteModal = true
        // this.events.forEach((item, index) => {
        //   if (this.events[index].title === this.space.title) {
        //     this.events.splice(index, 1)
        //     this.visible = false
        //     this.deleteOk = true
        //   }
        // })
      },
      dayClick(day, jsEvent) {
        console.log('dayClick', day, jsEvent)
      },
      moreClick(day, events, jsEvent) {
        console.log('moreCLick', day, events, jsEvent)
      },
      handleClick() {
        this.open = !this.open;
      },
      handleChange(date) {
        console.log(date)
        this.value3 = date;
      },
      saveCreateMeet() {
        this.createMeet = true
        this.formLeft = {}
        this.formLeft.endTime = new Date()
        this.$refs['meetForm'].resetFields()
      },
      createMeetYes() {
        this.meetstart = this.$moment(this.formLeft.startTime).format('YYYY-MM-DD HH:mm')
        this.meetEnd = this.$moment(this.formLeft.endTime).format('YYYY-MM-DD HH:mm')
        if (this.vertical = '本地会议') {
          this.type = 0
        } else {
          this.type = 1
        }
        if (this.judgeEdit) {
          this.changeMetting({
            id: this.meetId,
            pid: this.roomPid,
            title: this.formLeft.meetTitle,
            type: this.type,
            proposer: this.formLeft.applyPeople,
            number: this.formLeft.joinNum,
            startDate: Date.parse(new Date(this.formLeft.startTime)) / 1000,
            endDate: Date.parse(new Date(this.formLeft.endTime)) / 1000,
            content: this.formLeft.meetContent
          }).then(() => {
            this.createMeet = false
            this.createEventsList()
          }).catch(err => {
            console.log('changeMetting error: ' + err)
          })
        } else {
          this.$refs.meetForm.validate((valid) => {
            if (!valid) {
              this.createMeet = true
            } else {
              const currentTime = this.$moment(new Date()).format('YYYY-MM-DD HH:mm')
              var addMeeting = false
              if (this.meetstart >= this.meetEnd) {
                this.createMeet = true
                this.$Notice.open({
                  title: '提示',
                  desc: '开始时间不能大于或等于结束时间',
                  duration: 1
                })
              } else {
                for (var i = 0; i < this.events.length; i++) {
                  if (this.events[i].start === this.meetstart || this.events[i].end === this.meetEnd || (this.events[i].start === this.meetstart && this.events[i].end === this.meetEnd)) {
                    addMeeting = true
                    // this.$Notice.open({
                    //   title: '提示',
                    //   desc: '该时间段内不能添加会议',
                    //   duration: 1
                    // })
                  }
                }
              }
              if (addMeeting) {
                this.$Notice.open({
                  title: '提示',
                  desc: '该时间段内不能添加会议',
                  duration: 1
                })
              } else {
                addMeeting = false
                const meetingData = {
                  pid: this.roomPid,
                  title: this.formLeft.meetTitle,
                  type: this.type,
                  proposer: this.formLeft.applyPeople,
                  number: this.formLeft.joinNum,
                  startDate: Date.parse(new Date(this.formLeft.startTime)) / 1000,
                  endDate: Date.parse(new Date(this.formLeft.endTime)) / 1000,
                  content: this.formLeft.meetContent
                }
                this.createMetting(meetingData).then(() => {
                  this.createMeet = false
                  this.createEventsList()
                }).catch(err => {
                  console.log('getVideoAmountCount error: ' + err)
                })
              }
            }
          })
        }
      },
      cancelCreate() {
        this.createMeet = false
        this.$refs['meetForm'].resetFields()
      },
      //删除事件
      deleteOk() {
        this.meetId = this.space.meetId
        this.deleteMetting({ id: this.meetId }).then(() => {
          this.events.forEach((item, index) => {
            if (this.events[index].title === this.space.title) {
              this.events.splice(index, 1)
            }
          })
          this.deleteModal = false
        }).catch(err => {
          console.log('getVideoAmountCount error: ' + err)
        })
      },
      deleteCancel() {
        this.deleteModal = false
      },
      // 会议室选择
      meetRoomSelect() {

      },
      // 表单会议室选择
      formLeftSelect() {
        console.log(this.meetRoomData)
        this.meetRoomData.forEach((item, index) => {
          if (item.name === this.formLeft.model1) {
            this.roomPid = item.roomId
            this.formLeft.address = item.address
          }
        })
      },
      // 人员选择
      formPeopleSelect() {

      },
      dayClick() {
        console.log(6666)
      }
    }
  }

</script>
<style lang="less" scoped>
  @import "~fullcalendar/dist/fullcalendar.css";
  .meeting {
    color: #414141;
    /*// width: ~'calc(100% - 360px)';*/
    height: 100%;
    min-width: 1100px;
    border-radius: 10px;
    .little-data {
      float: left;
      width: 190px;
      position: relative;
      height: 100%;
      margin-right: 20px;
      .meetBtn {
        margin-top: 20px;
      }
    }
    .big-data {
      position: relative;
      float: left;
      width: ~"calc(100% - 240px)";
      .bs-table {
        border-bottom: 0px;
        margin: 10px 10px 10px 0;
        .bs-table-body .bs-table-row {
          height: 150px;
          .bs-table-row-item {
            height: 150px;
          }
        }
      }
    }
    #poss {
      .meetCard {
        p {
          padding: 2px 0;
          i {
            font-style: normal;
            font-size: 12px;
          }
        }
      }
      .titleStatus {
        height: 10px;
        width: 10px;
        float: right;
        margin-top: 5px;
      }
      .noStart {
        background-color: #f7b84f;
      }
      .yesEnd {
        background-color: #19be6b;
      }
      .progress {
        background-color: #2d8cf0;
      }
    }
  }
</style>